package org.sean.framework.test.canary.feign;

import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.sean.framework.bean.BaseResult;
import org.sean.framework.code.StatusInfo;
import org.sean.framework.exception.StatusException;
import org.sean.framework.logging.Logger;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "demo", fallbackFactory = UserClient.UserFallbackFactory.class)
public interface UserClient {
    Logger log = Logger.newInstance(UserClient.class);

    @GetMapping("/user/{id}")
    BaseResult<User> getUser(@PathVariable("id") Long id);


    @Component
    class UserFallbackFactory implements FallbackFactory<UserClient> {

        private StatusInfo error() {
            return StatusInfo.accessMsError().setAnyMessage("业务繁忙,请稍后再试");
        }

        @Override
        public UserClient create(Throwable cause) {
            log.printWarnStackTrace(cause);
            if (cause instanceof FeignException && ((FeignException) cause).status() == 403) {
                return (UserClient) Proxy.newProxyInstance(UserClient.class.getClassLoader(),
                        new Class[]{UserClient.class}, (proxy, method, args) -> BaseResult.error(error()));
            } else {
                throw new StatusException(error());
            }
        }

    }
}
